package com.dhcc.sds.base.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.annotion.CacheClear;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.sds.base.cache.qcentity.IQcEntityCache;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 质控病种字典
 * 
 * @ClassName: SdsQcentityController
 * @Description: TODO
 * @author sunyingjie
 * @date 2021-03-22 10:10:52
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdsqcentity")
public class SdsQcentityController extends BaseController {

	private String PREFIX = "/backend/sds/sdsqcentity/";

	@Autowired
	private ISdsQcentityService sdsQcentityService;
	@Autowired
    private ISdsCommonService sdsCommonService;
	

    /**
     * 跳转到质控病种字典列表首页
     */
    @RequestMapping("")
    public String index(Model model) {
        // 疾病分类
        JSONObject entityCatMap = sdsCommonService.getDicMap("EntityCat");
        model.addAttribute("entityCatMap",entityCatMap);
        //获取科室信息
        JSONObject deptMap = sdsCommonService.findDeptList();
        model.addAttribute("deptMap",deptMap);
        return PREFIX + "sdsqcentity.html";
    }
	
    /**
     * 跳转到新增质控病种字典
     */
    @RequestMapping("/to_add")
    public String toAdd(Model model) {
        // 疾病分类
        JSONObject entityCatMap = sdsCommonService.getDicMap("EntityCat");
        model.addAttribute("entityCatMap",entityCatMap);
        // 疾病类型
        JSONObject entityTypeMap = sdsCommonService.getDicMap("QcentityType");
        model.addAttribute("entityTypeMap",entityTypeMap);
        //获取科室信息
        JSONObject deptMap = sdsCommonService.findDeptList();
        model.addAttribute("deptMap",deptMap);
        return PREFIX + "sdsqcentity_add.html";
    }
	
	/**
     * 跳转到修改质控病种字典
     */
    @RequestMapping("/to_update/{sdsQcentityId}")
    public String toUpdate(@PathVariable Long sdsQcentityId, Model model) {
        SdsQcentityEntity sdsQcentity = this.sdsQcentityService.selectById(sdsQcentityId);
        // 疾病分类
        JSONObject entityCatMap = sdsCommonService.getDicMap("EntityCat");
        model.addAttribute("sdsQcentity",sdsQcentity);
        model.addAttribute("entityCatMap",entityCatMap);
        // 疾病类型
        JSONObject entityTypeMap = sdsCommonService.getDicMap("QcentityType");
        model.addAttribute("entityTypeMap",entityTypeMap);
        //获取科室信息
        JSONObject deptMap = sdsCommonService.findDeptList();
        model.addAttribute("deptMap",deptMap);
        return PREFIX + "sdsqcentity_edit.html";
    }

    /**
     * 获取质控病种字典列表
     */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params) {
		Page<SdsQcentityEntity> page = new PageFactory<SdsQcentityEntity>().defaultPage();
        List<SdsQcentityEntity> result = this.sdsQcentityService.page(page,params);
        page.setRecords((List<SdsQcentityEntity>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }

    /**
     * 获取质控病种字典列表(不分页)
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/noPageList")
    @ResponseBody
    public Object noPageList(@RequestParam Map<String, Object> params) {
        List<SdsQcentityEntity> result = this.sdsQcentityService.list(params);
        return result;
    }

    /**
     * 只获取病种名和id
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/listBtDesc")
    @ResponseBody
    public Object listBtDesc() {
        List<SdsQcentityEntity> result = this.sdsQcentityService.listBtDesc();
        return result;
    }



    /**
     * 新增质控病种字典
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @CacheClear(IQcEntityCache.CACHE_NAME)
    public Object add(SdsQcentityEntity sdsQcentity) {
        if (CommonUtil.isOneEmpty(sdsQcentity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        sdsQcentity.insert();
        return R.ok();
    }

    /**
     * 删除质控病种字典
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @CacheClear(IQcEntityCache.CACHE_NAME)
    public Object delete(@RequestParam Long sdsQcentityId) {
	
        this.sdsQcentityService.deleteById(sdsQcentityId);

        return R.ok();
    }

    /**
     * 修改质控病种字典
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @CacheClear(IQcEntityCache.CACHE_NAME)
    public Object update(SdsQcentityEntity sdsQcentity) {
        if (CommonUtil.isOneEmpty(sdsQcentity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsQcentityEntity old = this.sdsQcentityService.selectById(sdsQcentity.getId());

        old.setAbbrev(sdsQcentity.getAbbrev());
        old.setBtDesc(sdsQcentity.getBtDesc());
        old.setPubDate(sdsQcentity.getPubDate());
        old.setCost(sdsQcentity.getCost());
        old.setInDays(sdsQcentity.getInDays());
        old.setIndNo(sdsQcentity.getIndNo());
        old.setUrl(sdsQcentity.getUrl());
        old.setVersionId(sdsQcentity.getVersionId());
        old.setEntityCatId(sdsQcentity.getEntityCatId());
        old.setEntityTypeId(sdsQcentity.getEntityTypeId());
        old.setHospId(sdsQcentity.getHospId());
        old.setLinkDept(sdsQcentity.getLinkDept());
        old.setIsActive(sdsQcentity.getIsActive());
        old.setOperKey(sdsQcentity.getOperKey());
        old.setCdssName(sdsQcentity.getCdssName());
        old.updateAllColumnById();
        return R.ok();
    }

    /**
     * 获取病种分类的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> entityTree() {
        return sdsQcentityService.getEntityTree();
    }

    /**
     * 获取病种分类的tree列表
     */
    @RequestMapping(value = "/treebycode/{typeCode}")
    @ResponseBody
    public List<ZTreeNode> entityTreeByTypeCode(@PathVariable String typeCode) {
        return sdsQcentityService.getEntityTreeByTypeCode(typeCode);
    }

    /**
     * 导出病种
     */
    @RequestMapping("/export")
    public void exportUsers(@RequestParam(required = false) String entityCatId,
                            @RequestParam(required = false) String btDesc,
                            HttpServletRequest request,
                            HttpServletResponse response) {

        Map params = new HashMap();
        params.put("entityCatId", entityCatId);
        params.put("btDesc", btDesc);
        List<SdsQcentityEntity> result = this.sdsQcentityService.list(params);

        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        writer.renameSheet("病种字典");
        // 一次性写出内容，使用默认样式
        if (CommonUtil.isNotEmpty(result)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            for (SdsQcentityEntity obj : result) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("病种编码", obj.getAbbrev());
                row.put("病种名称", obj.getBtDesc());
                row.put("接口地址", obj.getUrl());
                row.put("发布时间", DateUtil.getDay(obj.getPubDate()));
                row.put("参考费用", obj.getCost());
                row.put("参考住院日", obj.getInDays());
                row.put("手术关键字", obj.getOperKey());
                row.put("是否有效", obj.getIsActive()!=0?"是":"否");
                row.put("入组序号", obj.getIndNo());
                row.put("疾病系统名称", obj.getEntityCat().getDescription());
                rows.add(row);
            }
            writer.write(rows);
            writer.setColumnWidth(1, 20);
            writer.setColumnWidth(2, 30);
            writer.setColumnWidth(3, 15);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        ServletOutputStream out = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "单病种字典_" + sdf.format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
            out = response.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }

    /**
     * 跳转到导入病种的页面
     */
    @RequestMapping("/to_import")
    public String toImport() {
        return PREFIX + "import.html";
    }

    /**
     * 导入病种字典
     */
    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    @CacheClear(IQcEntityCache.CACHE_NAME)
    public R impEntities(@RequestPart("file") MultipartFile file) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> all = reader.read();
            this.sdsQcentityService.importEntities(all);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }
	
}
